<template>
  <view class="register-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <view class="navbar-title">注册</view>
      <view class="navbar-right">
        <uni-icons type="more-filled" size="20" color="#333"></uni-icons>
      </view>
    </view>

    <scroll-view class="scroll-content" scroll-y>
      <view class="form-container">
        <!-- 负责人信息 -->
        <view class="form-section">
          <view class="form-item">
            <text class="form-label">负责人</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="输入负责人姓名"
              v-model="registerForm.ownerName"
            />
          </view>

          <view class="form-item">
            <text class="form-label">身份证号码</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="输入负责人身份证号码"
              maxlength="18"
              v-model="registerForm.idNumber"
            />
          </view>

          <view class="form-item">
            <text class="form-label">手机号</text>
            <input 
              class="form-input" 
              type="number" 
              placeholder="输入手机号"
              maxlength="11"
              v-model="registerForm.phone"
            />
          </view>

          <view class="form-item code-item">
            <text class="form-label">验证码</text>
            <input 
              class="form-input code-input" 
              type="number" 
              placeholder="输入验证码"
              maxlength="6"
              v-model="registerForm.verifyCode"
            />
            <button 
              class="code-btn" 
              :disabled="isCountingDown || !isValidPhone"
              @click="getVerificationCode"
            >
              {{ isCountingDown ? `${countdown}s后重新获取` : '获取验证码' }}
            </button>
          </view>
        </view>
		
		
<!-- 		<view>
			<button @tap="open">打开</button>
			<cityPicker :column="column" :default-value="defaultValue" :mask-close-able="maskCloseAble" @confirm="confirm" @cancel="cancel" :visible="visible"/>
			<view>{{str}}</view>
		</view> -->

        <!-- 店铺信息 -->
        <view class="form-section">
          <view class="form-item">
            <text class="form-label">店名</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="输入店名"
              v-model="registerForm.shopName"
            />
          </view>

          <view class="form-item">
            <text class="form-label">工商营业执照号码</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="输入营业执照号"
              v-model="registerForm.businessLicense"
            />
          </view>

          <!-- 替换为cityPicker的区域选择 -->
		<view class="form-item">
			<text class="form-label">经营区域</text>
			<view class="picker-input" @click="openAreaPicker">
			  <text class="picker-text" :class="{ placeholder: !selectedAreaText }">
				{{ selectedAreaText || '选择省市区' }}
			  </text>
			  <uni-icons type="down" size="16" color="#999"></uni-icons>
			</view>
			<cityPicker 
			  :column="3" 
			  :default-value="defaultAreaValue" 
			  :mask-close-able="true"
			  @confirm="onAreaConfirm"
			  @cancel="onAreaCancel"
			  :visible="areaPickerVisible"
			></cityPicker>
		  </view>

          <view class="form-item">
            <text class="form-label">地址</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="输入详细地址"
              v-model="registerForm.address"
            />
          </view>

          <view class="form-item textarea-item">
            <text class="form-label">商家介绍</text>
            <textarea 
              class="form-textarea" 
              placeholder="请输入商家介绍"
              maxlength="500"
              v-model="registerForm.description"
            ></textarea>
          </view>
        </view>
		
		
		 <!-- 在地址表单项下方添加地图选点区域 -->
		    <view class="form-section">
		      <view class="form-item">
		        <text class="form-label">店铺位置</text>
		        <button class="map-picker-btn" @click="openMapPicker">
		          <text v-if="registerForm.location">已选择位置</text>
		          <text v-else>点击选择位置</text>
		          <uni-icons type="map" size="16" color="#007aff"></uni-icons>
		        </button>
		      </view>
		      
		      <!-- 显示位置信息和地图预览 -->
		      <view v-if="registerForm.location" class="location-info">
		        <view class="location-text">
		          <text>经度: {{ registerForm.location.longitude }}</text>
		          <text>纬度: {{ registerForm.location.latitude }}</text>
		          <text>地址: {{ registerForm.location.address }}</text>
		        </view>
		        <map 
		          class="location-map"
		          :latitude="registerForm.location.latitude"
		          :longitude="registerForm.location.longitude"
		          :markers="markers"
		          scale="16"
		          show-location
		        ></map>
		      </view>
		    </view>
		
		    <!-- 地图选点弹窗 -->
		    <uni-popup ref="mapPopup" type="bottom" background-color="#fff">
		      <view class="map-container">
		        <map 
		          id="locationMap"
		          class="location-map-full"
		          :latitude="currentLocation.latitude"
		          :longitude="currentLocation.longitude"
		          :markers="markers"
		          scale="16"
		          show-location
		          @tap="onMapTap"
		        ></map>
		        
		        <view class="map-controls">
		          <button class="map-btn" @click="getCurrentPosition">
		            <uni-icons type="location-filled" size="20" color="#007aff"></uni-icons>
		            我的位置
		          </button>
		          <button class="map-btn confirm-btn" @click="confirmLocation">
		            确认选择
		          </button>
		        </view>
		      </view>
		    </uni-popup>
		

        <!-- 证件照片上传 -->
        <view class="form-section">
          <view class="upload-section">
            <text class="section-title">身份证正反面照片</text>
            <view class="upload-grid">
              <view class="upload-item" @click="uploadImage('idCardFront')">
                <image 
                  v-if="registerForm.idCardFront" 
                  :src="registerForm.idCardFront" 
                  class="upload-image"
                  mode="aspectFill"
                ></image>
                <view v-else class="upload-placeholder">
                  <uni-icons type="plus" size="30" color="#ccc"></uni-icons>
                  <text class="upload-text">上传照片</text>
                </view>
              </view>
              <view class="upload-item" @click="uploadImage('idCardBack')">
                <image 
                  v-if="registerForm.idCardBack" 
                  :src="registerForm.idCardBack" 
                  class="upload-image"
                  mode="aspectFill"
                ></image>
                <view v-else class="upload-placeholder">
                  <uni-icons type="plus" size="30" color="#ccc"></uni-icons>
                  <text class="upload-text">上传照片</text>
                </view>
              </view>
            </view>
          </view>

          <view class="upload-section">
            <text class="section-title">营业执照</text>
            <view class="upload-item single" @click="uploadImage('businessLicensePhoto')">
              <image 
                v-if="registerForm.businessLicensePhoto" 
                :src="registerForm.businessLicensePhoto" 
                class="upload-image"
                mode="aspectFill"
              ></image>
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="30" color="#ccc"></uni-icons>
                <text class="upload-text">上传照片</text>
              </view>
            </view>
          </view>

          <view class="upload-section">
            <text class="section-title">门面照片</text>
            <view class="upload-item single" @click="uploadImage('storeFront')">
              <image 
                v-if="registerForm.storeFront" 
                :src="registerForm.storeFront" 
                class="upload-image"
                mode="aspectFill"
              ></image>
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="30" color="#ccc"></uni-icons>
                <text class="upload-text">上传照片</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 注册按钮 -->
        <view class="register-btn-container">
          <button class="register-btn" @click="handleRegister">注册</button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker'
import { uploadApi } from '@/api/upload.js'
import { authApi } from '@/api/login.js'
import { registerApi } from '@/api/register.js'

const registerForm = ref({
  ownerName: '',
  idNumber: '',
  phone: '',
  verifyCode: '',
  shopName: '',
  businessLicense: '',
  area: '',
  address: '',
  description: '',
  idCardFront: '',
  idCardBack: '',
  businessLicensePhoto: '',
  storeFront: '',
  latitude: null,   // 纬度
  longitude: null    // 经度
})

const countdown = ref(0)
const isCountingDown = ref(false)
const areaIndex = ref(-1)
const areaList = ref([
  '朝阳区', '海淀区', '西城区', '东城区', '丰台区', 
  '石景山区', '门头沟区', '房山区', '通州区', '顺义区',
  '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区'
])


// 响应式数据
const visible = ref(false)
const maskCloseAble = ref(true)
const str = ref('')
const defaultValue = ref('420103') // 或 ['河北省','唐山市','丰南区']
const column = ref(3)

// 区域选择器相关状态
const areaPickerVisible = ref(false)
const selectedAreaText = ref('')
const defaultAreaValue = ref(['河南省', '郑州市', '中原区']) // 默认选择北京朝阳区

const BASE_URL = 'http://localhost:8080'
let timer = null



// 新增地图相关状态
const mapPopup = ref(null)
const currentLocation = ref({
  latitude: 39.90469,  // 默认北京中心坐标
  longitude: 116.40717
})
const selectedLocation = ref(null)
const markers = ref([
  {
    id: 1,
    latitude: 39.90469,
    longitude: 116.40717,
    iconPath: '/static/location-marker.png',
    width: 30,
    height: 30
  }
])

// 初始化获取当前位置
onMounted(() => {
  getCurrentPosition()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
})

// 打开地图选择器
const openMapPicker = () => {
  mapPopup.value.open()
}

// 获取当前位置
const getCurrentPosition = () => {
  uni.showLoading({ title: '定位中...' })
  
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      uni.hideLoading()
      currentLocation.value = {
        latitude: res.latitude,
        longitude: res.longitude
      }
      
      // 更新标记点
      markers.value = [{
        id: 1,
        latitude: res.latitude,
        longitude: res.longitude,
        iconPath: '/static/location-marker.png',
        width: 30,
        height: 30
      }]
    },
    fail: (err) => {
      uni.hideLoading()
      uni.showToast({
        title: '获取位置失败',
        icon: 'none'
      })
      console.error('定位失败:', err)
    }
  })
}

// 地图点击事件
const onMapTap = (e) => {
  const { latitude, longitude } = e.detail
  currentLocation.value = { latitude, longitude }
  
  // 更新标记点
  markers.value = [{
    id: 1,
    latitude,
    longitude,
    iconPath: '/static/location-marker.png',
    width: 30,
    height: 30
  }]
}

// 确认选择位置
const confirmLocation = () => {
  if (currentLocation.value) {
    registerForm.value.latitude = currentLocation.value.latitude
	registerForm.value.longitude = currentLocation.value.longitude
    mapPopup.value.close()
	console.log("所选位置经纬度:",currentLocation.value)
  } else {
    uni.showToast({
      title: '请先选择位置',
      icon: 'none'
    })
  }
}



const isValidPhone = computed(() => {
  return /^1[3-9]\d{9}$/.test(registerForm.value.phone)
})

const goBack = () => {
  uni.navigateBack()
}

const getVerificationCode = async () => {
  if (!isValidPhone.value) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  
  isCountingDown.value = true
  countdown.value = 60
  
  try {
    // 4. 显示加载状态
    uni.showLoading({
      title: '发送中...',
      mask: true
    })
    
    // 5. 调用真实接口
    await authApi.sendSms({"phone":registerForm.value.phone})
    
    // 6. 发送成功处理
    uni.hideLoading()
    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })
    
    // 7. 开始倒计时
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        timer = null
      }
    }, 1000)
    
  } catch (error) {
    // 8. 错误处理
    uni.hideLoading()
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}

const onAreaChange = (e) => {
  areaIndex.value = e.detail.value
  registerForm.value.area = areaList.value[e.detail.value]
}

const uploadImage = (type) => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['camera', 'album'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      
      // 先显示预览图
      registerForm.value[type] = tempFilePath
      
      try {
        uni.showLoading({
          title: '上传中...',
          mask: true
        })
        
        // 小程序环境使用 uni.uploadFile
        const uploadResult = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: BASE_URL + '/file/uploadOSS',
            filePath: tempFilePath,
            name: 'file',
            formData: {
              // 可以添加其他表单字段
            },
            header: {
              'Authorization': `Bearer ${uni.getStorageSync('token')}`,
              'Content-Type': 'multipart/form-data'
            },
            success: (res) => {
              if (res.statusCode === 200) {
                const data = JSON.parse(res.data)
                if (data.code === 200) {
                  resolve(data)
                } else {
                  reject(new Error(data.msg || '上传失败'))
                }
              } else {
                reject(new Error(`HTTP错误: ${res.statusCode}`))
              }
            },
            fail: (err) => {
              reject(err)
            }
          })
        })
        
        registerForm.value[type] = uploadResult.data.url
        console.log("图片路径：", uploadResult.data.url)
        
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('上传失败:', error)
        registerForm.value[type] = ''
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    fail: (err) => {
      console.log('选择图片失败：', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

const validateForm = () => {
  const form = registerForm.value
  
  if (!form.ownerName) {
    uni.showToast({ title: '请输入负责人姓名', icon: 'none' })
    return false
  }
  
  if (!form.idNumber || !/^\d{17}[\dXx]$/.test(form.idNumber)) {
    uni.showToast({ title: '请输入正确的身份证号码', icon: 'none' })
    return false
  }
  
  if (!isValidPhone.value) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return false
  }
  
  if (!form.verifyCode || form.verifyCode.length !== 6) {
    uni.showToast({ title: '请输入6位验证码', icon: 'none' })
    return false
  }
  
  if (!form.shopName) {
    uni.showToast({ title: '请输入店名', icon: 'none' })
    return false
  }
  
  if (!form.businessLicense) {
    uni.showToast({ title: '请输入营业执照号码', icon: 'none' })
    return false
  }
  
  if (!form.area) {
    uni.showToast({ title: '请选择经营区域', icon: 'none' })
    return false
  }
  
  if (!form.address) {
    uni.showToast({ title: '请输入详细地址', icon: 'none' })
    return false
  }
  
  if (!form.idCardFront || !form.idCardBack) {
    uni.showToast({ title: '请上传身份证正反面照片', icon: 'none' })
    return false
  }
  
  if (!form.businessLicensePhoto) {
    uni.showToast({ title: '请上传营业执照照片', icon: 'none' })
    return false
  }
  
  if (!form.storeFront) {
    uni.showToast({ title: '请上传门面照片', icon: 'none' })
    return false
  }
  
  return true
}

const handleRegister = async() => {
  if (!validateForm()) {
    return
  }
  
  uni.showLoading({
    title: '注册中...'
  })
  try{
  
  // 调用真实的注册API
    const res = await registerApi.registerByMerchant({
      ...registerForm.value
    })
    
    // 根据后端返回的状态码判断是否成功
    if (res.code === 200) {
      uni.hideLoading()
      uni.showModal({
        title: '注册成功',
        content: res.message || '您的注册申请已提交，请等待审核',
        showCancel: false,
        success: () => {
          // 注册成功后跳转回登录页或其他页面
          uni.navigateBack()
        }
      })
      
      // 可以在这里记录注册成功日志或发送事件统计
      console.log('注册成功:', res.data)
    } else {
      uni.hideLoading()
      uni.showToast({
        title: res.message || '注册失败，请稍后重试',
        icon: 'none',
        duration: 3000
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('注册请求异常:', error)
    
    // 根据错误类型显示不同的提示
    let errorMessage = '网络异常，请检查网络连接'
    if (error.response) {
      // 请求已发出，服务器返回状态码不在 2xx 范围内
      errorMessage = error.response.data?.message || `服务器错误: ${error.response.status}`
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = '请求超时，请稍后重试'
    }
    
    uni.showModal({
      title: '注册失败',
      content: errorMessage,
      showCancel: false
    })
  }
}


// 方法
const open = () => {
  visible.value = true
}

const confirm = (val) => {
  console.log(val)
  str.value = JSON.stringify(val)
  visible.value = false
}

const cancel = () => {
  visible.value = false
}

// 打开地区选择器
const openAreaPicker = () => {
  areaPickerVisible.value = true
}

// 地区选择确认
// 地区选择确认 - 根据新的数据结构调整
const onAreaConfirm = (result) => {
  console.log('区域选择结果:', result); // 调试用
  
  if (result && result.provinceName && result.cityName && result.areaName) {
    // 存储完整的区域信息
    registerForm.value.area = `${result.provinceName}${result.cityName}${result.areaName}`;
    // 显示格式：省+市+区
    selectedAreaText.value = `${result.provinceName}${result.cityName}${result.areaName}`;
    
    // 如果需要存储区域代码
    registerForm.value.areaCode = result.code; // 420103
    
    // 如果需要分别存储省市区
    registerForm.value.province = result.provinceName;
    registerForm.value.city = result.cityName;
    registerForm.value.district = result.areaName;
  } else {
    console.error('区域选择数据格式不正确:', result);
    uni.showToast({
      title: '区域选择失败，请重试',
      icon: 'none'
    });
  }
  
  areaPickerVisible.value = false;
}

// 地区选择取消
const onAreaCancel = () => {
  areaPickerVisible.value = false
}

</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.custom-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-left,
.navbar-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.scroll-content {
  height: calc(100vh - 88rpx);
}

.form-container {
  padding: 0 30rpx 40rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin-top: 20rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  min-height: 80rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  width: 200rpx;
  font-size: 32rpx;
  color: #333;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 32rpx;
  background-color: #fafafa;
}

.form-input:focus {
  border-color: #007aff;
  background-color: #fff;
}

.code-item {
  align-items: stretch;
}

.code-input {
  margin-right: 20rpx;
}

.code-btn {
  width: 200rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #007aff, #5856d6);
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
  flex-shrink: 0;
}

.code-btn:disabled {
  background: #e8e8e8;
  color: #999;
}

.picker-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker-text {
  font-size: 32rpx;
  color: #333;
}

.picker-text.placeholder {
  color: #999;
}

.textarea-item {
  align-items: flex-start;
  padding-top: 20rpx;
}

.form-textarea {
  flex: 1;
  min-height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 32rpx;
  background-color: #fafafa;
  line-height: 1.5;
}

.upload-section {
  margin-bottom: 40rpx;
}

.upload-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.upload-grid {
  display: flex;
  gap: 20rpx;
}

.upload-item {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  position: relative;
  overflow: hidden;
}

.upload-item.single {
  width: 100%;
  height: 200rpx;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.upload-text {
  font-size: 26rpx;
  color: #999;
}

.upload-image {
  width: 100%;
  height: 100%;
}

.register-btn-container {
  margin-top: 60rpx;
  padding: 0 30rpx;
}

.register-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #007aff, #5856d6);
  color: white;
  border: none;
  border-radius: 16rpx;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
}

.register-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.4);
}
</style>
